module.exports =  function wx_request({
  base_url,
  timeout = 3000,
  header,
  statusCode,
}) {
  /**
   *请求request
   *url:_url 请求路径
   *method:方法格式
   *data:请求体
   *header: 'content-type': 'application/x-www-form-urlencoded' // 默认值
   *dataType: 'json', //返回格式
   * success:成功的回调
   * fail:失败的回调
   * complete:成功失败都会执行
   */

  /**
   * 请求拦截器
   */
  const RequestIntereptor = {
    /**
     * @param { type Array } interceptors 
     * @param { type Function} use 
     */
    interceptors: [],
    use(func) {
      RequestIntereptor.interceptors.push(func);
    },
    /**
     * 
     * @param {*} resolve 
     * @param {*} response 
     * @param {*} method 
     * @param {*} url 
     * @param {*} data 
     * @param {*} reject 
     */
    async intercept(config, method, url, cache, reqIntercept, resIntercept,app_configs) {
      if (!reqIntercept) {
        for (let i = 0; i < this.interceptors.length; i++) {
          config = await this.interceptors[i](config, method, url, cache,reqIntercept,app_configs );
        }
        return config
      }
      return config
    },
  };
  /**
   * 响应拦截器
   */
  const ResponseIntereptor = {
    interceptors: [],
    use(func) {
      ResponseIntereptor.interceptors.push(func);
    },
    async intercept(resolve, response, method, url, data,  reqIntercept, resIntercept,app_configs) {
      //  走响应拦截器
      if (!resIntercept) {
        for (let i = 0; i < this.interceptors.length; i++) {
          response = await this.interceptors[i](response, method, url, data,app_configs)
        }
      }
      if (response.success) {
        resolve(typeof response.data === 'string' ? JSON.parse(response.data) : response.data)
      } else {
          //  不走拦截器 
          resolve( response.data )
      }
    }
  };

  /**
   *  wx请求
   */
  const request = (method, url, data, cache, header, reqIntercept, resIntercept,app_configs = null) => {
    return new Promise((resolve, reject) => {
      RequestIntereptor.intercept({
        header: header || {},
        body: data || {}
      }, method, url, cache, reqIntercept, resIntercept,app_configs).then(({
        header,
        body: data
      }) => {
        // 是否走缓存
        // console.log(cache)
        let request_key = `${url.toUpperCase()}:${method}`;
        if (cache) {
         cache_methds(request_key,async ( result ) => {
          //  console.log( result )
           if (result) {
             resolve(result)
           } else {
            console.debug('%---------------------------走缓存了,请求')
             wx_request(cache)
           }
          });
          
        } else {
          //  console.log('没做缓存','请求了')
          console.debug('%----------------------请求了(未做缓存)----------------------%')
           wx_request(cache)
        }
        function wx_request(cache) {
            wx.request({
             url: url[0] === '/' ? base_url + url : url,
             method: method, //请求方法
             data: data, // 请求体
             header: {
               'content-type': 'application/x-www-form-urlencoded' // 默认值
             },
             dataType: 'json', //返回格式
             responseType: 'text',
             success: function (res) {
                 if( cache) {
                   set_storage( request_key,res.data)
                 }
               ResponseIntereptor.intercept(resolve, {
                 success: true,
                 ...res
               }, method, url, data,  reqIntercept, resIntercept,app_configs)
             },
             fail: function () {
   
             },
             complete: function () {
   
             }
   
           })
        }
      })
    })
  };
  /**
   * cache 是否走缓存
   */
  async function cache_methds(request_key,call ) {
    //  console.log(url,method);
   //  let request_key = `${url.toUpperCase()}:${method}`;
    // console.log( request_key )
    let reslut = await read_storage(request_key);
    // console.log(reslut)
    console.log('走了缓存');
    call(reslut )
 
    /**
     * 读取缓存;
     * status 读取缓存的状态 
     */
  }

  //   读取 缓存
  function read_storage(request_key) {
    return new Promise((resolve, reject) => {
      wx.getStorage({
        key: request_key,
        success: StorageSuccess,
        fail: StorageError
      });

      function StorageSuccess(res) {
        resolve(res.data)
      };

      function StorageError(err) {
        // console.log(err)
        resolve(false)
      };
    })


  }

 //  进行缓存 
 function set_storage (request_key,data) {
   wx.setStorage({
     key:request_key,
     data,
     success() {

     },
     fail() {

     }
   })
 }
  const $post = (url, data, header, cache, ...args) => {
    console.log( )
    return request("POST", url, data, header, cache, ...args);
  };
  return {
    post: $post,
    RequestIntereptor,
    ResponseIntereptor
  };
}
